package com.neu.flashmall.product.service.impl;


import com.neu.common.utils.Result;
import com.neu.flashmall.product.entity.PmsSkuImages;
import com.neu.flashmall.product.feign.ThirdPartyFeignService;
import com.neu.flashmall.product.mapper.PmsSkuImagesMapper;
import com.neu.flashmall.product.service.PmsSkuImagesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PmsSkuImagesServiceImpl implements PmsSkuImagesService {

    @Resource
    private PmsSkuImagesMapper pmsSkuImagesMapper;

    @Resource
    private ThirdPartyFeignService thirdPartyFeignService;

    @Override
    public List<PmsSkuImages> getAllBySkuId(Long skuId) {
        return pmsSkuImagesMapper.getAllBySkuId(skuId);
    }

    @Override
    @Transactional
    public String setDefault(Long skuId,Long id) {
        PmsSkuImages old = this.pmsSkuImagesMapper.selectDefaultImg(skuId);
        if(old != null){
            old.setDefaultImg(0);
            this.pmsSkuImagesMapper.updateByPrimaryKeySelective(old);
        }
        PmsSkuImages out = new PmsSkuImages();
        out.setDefaultImg(1);
        out.setId(id);
        int result = this.pmsSkuImagesMapper.updateByPrimaryKeySelective(out);
        if(result == 1) return "更新成功";
        return "数据库异常";
    }

    @Override
    public String updateImage(PmsSkuImages pmsSkuImages) {
        int result = pmsSkuImagesMapper.updateByPrimaryKeySelective(pmsSkuImages);
        if(result == 1) return "更新成功";
        return "数据库异常";
    }

    @Override
    public String addImage(PmsSkuImages pmsSkuImages) {
        pmsSkuImages.setImgSort(0);
        pmsSkuImages.setDefaultImg(0);
        int result = this.pmsSkuImagesMapper.insertSelective(pmsSkuImages);
        if(result == 1) return "添加成功";
        return "数据库异常";
    }

    @Override
    public String deleteImage(Long id) {
        PmsSkuImages pmsSkuImages = this.pmsSkuImagesMapper.selectByPrimaryKey(id);
        if(pmsSkuImages == null) return "id错误";
        Result result1 = thirdPartyFeignService.deleteSkuOneImage(pmsSkuImages.getImg());
        if(result1.getCode() == 2000){
            int result = this.pmsSkuImagesMapper.deleteByPrimaryKey(id);
            if(result == 1) return "删除成功";
            return "数据库异常";
        }
        return "云服务器删除异常";
    }

}
